package org.liquidByte.simpleChat.guiClient;

import java.io.IOException;
import java.net.UnknownHostException;

import org.liquidByte.simpleChat.communication.Channel;
import org.liquidByte.simpleChat.communication.ChannelController;
import org.liquidByte.simpleChat.communication.ChannelFaultedEventListener;

class ClientController {
	private static ClientController current;
	private ChannelController channelController;
	private Channel channel;
	private ChatClient chatClient;
	
	ClientController() {
		this.channelController = new ChannelController(new RemoteCallHandlerImpl());
	}

	public ChatClient getChatClient() {
		if (this.chatClient == null && this.channel != null) {
			this.chatClient = new ChatClient(this.channel);
		}
		return this.chatClient;
	}
 
	private void _connect(String host, int port) throws UnknownHostException, IOException {
		this.channel = this.channelController.connect(host, port);
	}
	private boolean _isConnected() {
		return this.channel != null;
	}
	private void _addListener(ChannelFaultedEventListener faulted) {
		this.channelController.addListener(faulted);
	}
	private void _removeListener(ChannelFaultedEventListener faulted) {
		this.channelController.removeListener(faulted);
	}
	
	public static void connect(String host, int port) throws UnknownHostException, IOException {
		ClientController.getCurrent()._connect(host, port);
	}
	public static boolean isConnected() {
		return ClientController.getCurrent()._isConnected();
	}	
	public static ClientController getCurrent() {
		if (ClientController.current == null) {
			ClientController.current = new ClientController();
		}
		return ClientController.current;
	}
	public static void addListener(ChannelFaultedEventListener faulted) {
		ClientController.getCurrent()._addListener(faulted);
	}
	public static void removeListener(ChannelFaultedEventListener faulted) {
		ClientController.getCurrent()._removeListener(faulted);
	}
}
